class Solution {
public:
    void reverse(int x, int y, int len, vector<vector<int>>& matrix,
                 vector<vector<int>>& copy) {
        int y1 = y + len;
        int x1 = x + len;
        for (int i = y, xx = x1 - 1; i < y1; i++) {
            matrix[x][i] = copy[xx][y];
            xx--;
        }
        for (int i = x, yy = y; i < x1; i++) {
            matrix[i][y1 - 1] = copy[x][yy];
            yy++;
        }
        for (int i = y, xx = x1 - 1; i < y1; i++) {
            matrix[x1 - 1][i] = copy[xx][y1 - 1];
            xx--;
        }
        for (int i = x, yy = y; i < x1; i++) {
            matrix[i][y] = copy[x1 - 1][yy];
            yy++;
        }
    }
    void rotate(vector<vector<int>>& matrix) {
        vector<vector<int>> copy(matrix);
        int len = matrix.size();
        int x = 0, y = 0;
        while (len >= 1) {
            reverse(x, y, len, matrix, copy);
            x++;
            y++;
            len -= 2;
        }
    }
};